package edu.webarchitechture.bank.web.actions;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import edu.webarchitechture.bank.ejb3.domain.Account;
import edu.webarchitechture.bank.ejb3.services.AccountManager;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.List;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Action class to manage account related actions.
 *
 * @author Inoka Dissanayaka.
 */
public class AccontManagerAction  extends ActionSupport implements Preparable {

    /** AccountManager bean.*/
    private AccountManager accountManager;

    /** Represent all the savings accounts*/
    private List<Account> savingsAccounts;

    /**
     * This method will be executed before executing any of the action method in the action class.
     *
     * @throws Exception An exception
     */
    public void prepare() throws Exception {
        System.out.println("Account manager action prepare Called");

        try {
            Context c = new InitialContext();
            accountManager = (AccountManager) c.lookup("AccountManagerBean/local");
        } catch (NamingException ex) {
            System.out.println("NamingException Called");
        } catch (IllegalArgumentException ex) {
            System.out.println("IllegalArgumentException Called");
        }
    }

    public String showAccountSummery() {
        System.out.println("showAccountSummery() Called");

        try {
            //todo specify the current customer id for getting actual values.
            savingsAccounts = accountManager.getAccountsOfCustomer(1L);
        } catch (Exception e) {
            addActionError(e.getMessage());
            e.printStackTrace();
            return INPUT;
        }
        return SUCCESS;
    }

    public String getToday() {
        Date today = new Date();
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
        return df.format(today);
    }

    public List<Account> getSavingsAccounts() {
        return savingsAccounts;
    }

    public void setSavingsAccounts(List<Account> savingsAccounts) {
        this.savingsAccounts = savingsAccounts;
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }
}
